package com.black.cat.jvm.instructions.base;

import com.black.cat.jvm.rtda.Frame;
import com.black.cat.jvm.rtda.JThread;
import com.black.cat.jvm.rtda.Slot;
import com.black.cat.jvm.rtda.heap.methodarea.JMethod;

/**
 * @Author blackcat
 * @create 2021/8/16 14:20
 * @version: 1.0
 * @description:
 */
public class MethodInvokeLogic {

    public static void invokeMethod(Frame invokerFrame, JMethod method) {
        JThread thread = invokerFrame.thread();
        Frame newFrame = thread.newFrame(method);
        thread.pushFrame(newFrame);

        int argSlotCount = method.getArgSlotCount();
        if (argSlotCount > 0) {
            //TODO  在代码中，并没有对long和double类型做特别处理
            for (int i = argSlotCount - 1; i >= 0; i--) {
                Slot slot = invokerFrame.operandStack().popSlot();
                newFrame.localVars().setSlot(i, slot);
            }
        }

        //hack 本地方法
        if (method.isNative()) {
            if ("registerNatives".equals(method.name())) {
                thread.popFrame();
            } else {
                throw new RuntimeException("native method " + method.name());
            }
        }
    }
}
